package com.nzw.platform.monitor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nzw.common.cache.CacheType;
import com.nzw.redis.impl.common.RedisTemplate;
import com.nzw.utils.CacheUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by XuZhanSi on 2016/12/28 0028.
 */
@Component
public class ClientManager {

    @Autowired
    RedisTemplate redisTemplate;

    public void saveClient(String sessionId, Client client) {
        CacheUtil.saveKeyValue(CacheType.CLINET_ONLINE_CACHE, sessionId, client);//本地存储
        redisTemplate.set(CacheType.CLINET_ONLINE_CACHE.getName() + ":" + sessionId, JSONObject.toJSONString(client));//远程存储
    }

    /**
     * 获取用户
     *
     * @param sessionId
     * @return
     */
    public Client getClient(String sessionId) {
        if (sessionId == null)
            return null;
        Client client = (Client) CacheUtil.getCacheValue(CacheType.CLINET_ONLINE_CACHE, sessionId);
        if (client != null)
            return client;
        String cache = redisTemplate.get(CacheType.CLINET_ONLINE_CACHE.getName() + ":" + sessionId);
        if (cache == null)
            return null;
        client = JSON.parseObject(cache, Client.class);
        CacheUtil.saveKeyValue(CacheType.CLINET_ONLINE_CACHE, sessionId, client);//本地存储
        return client;
    }


    /**
     * 获取在线用户
     *
     * @return
     */
    public <T> T getCurrentUser(Class<T> clazz) {
        Subject subject = SecurityUtils.getSubject();
        String sessionId = (String) subject.getSession().getId();
        Client client = getClient(sessionId);
        T user = null;
        if (client != null && client.getOnlineUser() != null) {
            user = client.getOnlineUser() instanceof JSONObject ? JSON.parseObject(((JSONObject) client.getOnlineUser()).toJSONString(), clazz) : (T) client.getOnlineUser();
        }
        return client == null ? null : user;
    }

    /**
     * 更新在线用户信息
     *
     * @param user
     */
    public void updateCurrentUser(Object user) {
        String sessionId = (String) SecurityUtils.getSubject().getSession().getId();
        Client client = getClient(sessionId);
        if (client != null) {
            client.setOnlineUser(user);
            saveClient(sessionId, client);
        }
    }

    /**
     * 移除在线用户
     *
     * @param sessionId
     */
    public void removeClient(String sessionId) {
        CacheUtil.removeCacheValue(CacheType.CLINET_ONLINE_CACHE, sessionId);
        redisTemplate.del(CacheType.CLINET_ONLINE_CACHE.getName() + ":" + sessionId);
    }
}
